use std::{
    cell::{Ref, RefCell},
    rc::Rc,
};

struct Node<T> {
    element: T,
    prev: Link<T>,
    next: Link<T>,
}
impl<T> Node<T> {
    fn new(element: T) -> Rc<RefCell<Self>> {
        Rc::new(RefCell::new(Node {
            element,
            prev: None,
            next: None,
        }))
    }
}
type Link<T> = Option<Rc<RefCell<Node<T>>>>;

pub struct List<T> {
    head: Link<T>,
    tail: Link<T>,
}
impl<T> List<T> {
    pub fn new() -> Self {
        List {
            head: None,
            tail: None,
        }
    }
    pub fn push_front(&mut self, element: T) {
        let new_head = Node::new(element);
        match self.head.take() {
            Some(old_head) => {
                old_head.borrow_mut().prev = Some(new_head.clone());
                new_head.borrow_mut().next = Some(old_head);
                self.head = Some(new_head);
            }
            _ => {
                self.tail = Some(new_head.clone());
                self.head = Some(new_head);
            }
        }
    }
    pub fn pop_front(&mut self) -> Option<T> {
        self.head.take().map(|old_head| {
            match old_head.borrow_mut().next.take() {
                Some(new_head) => {
                    new_head.borrow_mut().prev.take();
                    self.head = Some(new_head);
                }
                None => {
                    self.tail.take();
                }
            }
            Rc::try_unwrap(old_head).ok().unwrap().into_inner().element
        })
    }
    pub fn peek_front(&self) -> Option<Ref<T>> {
        self.head.as_ref().map(|node| {
            let node = node.borrow();
            Ref::map(node, |node| &node.element)
        })
    }
    pub fn push_tail(&mut self, element: T) {
        let new_tail = Node::new(element);
        match self.tail.take() {
            Some(old_tail) => {
                old_tail.borrow_mut().next = Some(new_tail.clone());
                new_tail.borrow_mut().prev = Some(old_tail);
                self.tail = Some(new_tail);
            }
            _ => {
                self.tail = Some(new_tail.clone());
                self.head = Some(new_tail);
            }
        }
    }
    pub fn pop_tail(&mut self) -> Option<T> {
        self.tail.take().map(|old_tail| {
            match old_tail.borrow_mut().prev.take() {
                Some(tail) => {
                    tail.borrow_mut().next.take();
                    self.tail = Some(tail);
                }
                None => {
                    self.head.take();
                }
            }
            Rc::try_unwrap(old_tail).ok().unwrap().into_inner().element
        })
    }
    pub fn peek_tail(&self) -> Option<Ref<T>> {
        self.tail.as_ref().map(|node| {
            let node = node.borrow();
            Ref::map(node, |node| &node.element)
        })
    }
    pub fn into_iter(self) -> IntoIter<T> {
        IntoIter(self)
    }
}
impl<T> Drop for List<T> {
    fn drop(&mut self) {
        while self.pop_front().is_some() {}
    }
}
pub struct IntoIter<T>(List<T>);
impl<T> Iterator for IntoIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.pop_front()
    }
}
impl<T> DoubleEndedIterator for IntoIter<T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.0.pop_tail()
    }
}
#[cfg(test)]
mod test {
    use std::borrow::Borrow;

    use super::List;
    #[test]
    pub fn basics() {
        let mut list = List::new();

        // Check empty list behaves right
        assert_eq!(list.pop_front(), None);

        // Populate list
        list.push_front(1);
        list.push_front(2);
        list.push_front(3);

        // Check normal removal
        assert_eq!(list.pop_front(), Some(3));
        assert_eq!(list.pop_front(), Some(2));

        // Push some more just to make sure nothing's corrupted
        list.push_front(4);
        list.push_front(5);

        // Check normal removal
        assert_eq!(list.pop_front(), Some(5));
        assert_eq!(list.pop_front(), Some(4));

        // Check exhaustion
        assert_eq!(list.pop_front(), Some(1));
        assert_eq!(list.pop_tail(), None);
        list.push_tail(6);
        list.push_tail(7);
        list.push_tail(8);
        assert_eq!(list.pop_tail(), Some(8));
        assert_eq!(list.pop_tail(), Some(7));
        assert_eq!(list.pop_tail(), Some(6));
        assert_eq!(list.pop_tail(), None);
        assert_eq!(list.pop_front(), None);
    }
    #[test]
    pub fn peek() {
        let mut list = List::new();
        list.push_front(1);
        list.push_front(2);
        list.push_front(3);
        let n = list.peek_front().unwrap();
        // 通过隐式解引用，Ref<i32>可以直接使用i32的方法
        // 但是对于封装非确定性类型，则无法隐式解引用
        assert!(n.cmp(&3).is_eq());
        assert!(is_eq(n.borrow(), &3));
        assert!(is_eq(&n, &3));
        assert_eq!(&*list.peek_front().unwrap(), &3);
        assert_eq!(&*list.peek_tail().unwrap(), &1);
    }
    pub fn is_eq(a: &i32, b: &i32) -> bool {
        a == b
    }

    #[test]
    pub fn into_iter() {
        let mut list = List::new();
        list.push_front(1);
        list.push_front(2);
        list.push_front(3);
        list.push_front(4);
        let mut into_iter = list.into_iter();
        assert_eq!(into_iter.next(), Some(4));
        assert_eq!(into_iter.next_back(), Some(1));
        assert_eq!(into_iter.next_back(), Some(2));
        assert_eq!(into_iter.next(), Some(3));
        assert_eq!(into_iter.next(), None);
    }
}
